package com.zoe.onelink.logging.trace.sql.p6spy;

import com.p6spy.engine.common.ResultSetInformation;
import com.p6spy.engine.common.StatementInformation;
import com.p6spy.engine.logging.Category;
import com.p6spy.engine.logging.LoggingEventListener;
import com.zoe.onelink.logging.trace.sql.SqlExecuteContextHolder;

import java.sql.SQLException;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-03-08
 */
public class OnelinkLoggingEventListener extends LoggingEventListener {

    private static OnelinkLoggingEventListener INSTANCE;

    public static OnelinkLoggingEventListener getInstance() {
        if (null == INSTANCE) {
            INSTANCE = new OnelinkLoggingEventListener();
        }
        return INSTANCE;
    }

    @Override
    public void onBeforeAnyExecute(StatementInformation statementInformation) {
        logElapsed(statementInformation, 0L, Category.STATEMENT, null);
    }

    @Override
    public void onAfterAnyExecute(StatementInformation statementInformation, long timeElapsedNanos, SQLException e) {
        SqlExecuteContextHolder.set(SqlExecuteContextHolder.CONSUME, String.valueOf(timeElapsedNanos / 1_000_000));
    }

    @Override
    public void onAfterExecuteBatch(StatementInformation statementInformation, long timeElapsedNanos, int[] updateCounts, SQLException e) {
        // do nothing
    }

    @Override
    public void onAfterResultSetClose(ResultSetInformation resultSetInformation, SQLException e) {
        super.onAfterResultSetClose(resultSetInformation, e);
        if (resultSetInformation.getCurrRow() > -1) {
            SqlExecuteContextHolder.set(SqlExecuteContextHolder.ROWS, String.valueOf(resultSetInformation.getCurrRow() + 1));
        }
    }
}
